<template>
  <div class="content-title" :style="{ flexDirection: sunBurstData?.typeList?.length > 4 ? 'column' : '', marginBottom: !isGroundFloor ? (Math.ceil(sunBurstData?.typeList?.length / 4) === 2 ? '36px' : '62px') : '', ...magnifyFontSizeObj }">
    <span :class="sunBurstData?.typeList?.length > 4 ? 'content-title-label' : ''">{{ sunBurstData?.title }}</span>
    <div class="content-title-right" :style="{ flexDirection: sunBurstData?.typeList?.length > 4 ? 'column' : '' }">
      <template v-if="isGroundFloor" >
        <el-row :gutter="10" v-for="rowItem of Math.ceil(sunBurstData?.typeList?.length / 4)" :key="rowItem"
                :class="rowItem !== 1 ? 'multiple-row' : ''">
          <el-col :span="sunBurstData?.typeList?.length > 4 ? 6 : 24 / sunBurstData?.typeList?.length"
                  v-for="(colItem, index) of sunBurstData?.typeList?.filter((x, i) => i < 4 * rowItem && i >= (rowItem - 1) * 4)"
                  :key="index">
            <div class="content-title-item" @click="changeTabs(colItem)" :style="{ cursor: colItem.isDisabled ? 'default' : 'pointer' }">
              <div :style="{backgroundColor: colItem.show ? colItem.color : '#CBCBCB'}"></div>
              <div :style="{color: colItem.show ? 'white' : '#CBCBCB'}" style="white-space: nowrap; overflow: visible">{{ colItem.label }}</div>
            </div>
          </el-col>
        </el-row>
      </template>
      <template v-else>
        <el-row :gutter="10">
          <el-col :span="12" v-for="(colItem, index) of sunBurstData?.childrenTypeList" :key="index">
            <div class="content-title-item">
              <div :style="{backgroundColor: colItem.color}"></div>
              <div style="white-space: nowrap; overflow: visible; color: white">{{ currentChildrenLegendMainName }}-{{ colItem.label }}</div>
            </div>
          </el-col>
        </el-row>
      </template>
    </div>
  </div>
  <div ref="echartDom" v-bind="$attrs"></div>
</template>

<script setup>
import {ref, defineProps, onMounted, onUnmounted, inject, shallowRef, defineExpose, defineEmits} from 'vue'
import {pxToRem} from "@/utils/index";

const props = defineProps({
  sunBurstData: {
    type: Object,
    default: () => {
    }
  },
  dialogData: {
    type: Object,
    default: () => ({
      fontSizeTimes: 1
    })
  }
});

const emit = defineEmits(['changeLegend', 'changeFloor', 'magnifyChart', 'dialogEmit'])

const echartDom = ref(null);
const myChart = shallowRef(null);
const echarts = inject('echarts');

const isGroundFloor = ref(true)
const currentChildrenLegendMainName = ref('')

const magnifyFontSizeObj = ref({
  '--custom-font-size-10': pxToRem(props?.dialogData?.fontSizeTimes * 10) + 'px',
  '--custom-font-size-12': pxToRem(props?.dialogData?.fontSizeTimes * 12) + 'px',
  '--custom-font-size-14': pxToRem(props?.dialogData?.fontSizeTimes * 14) + 'px',
  '--custom-line-height-18': pxToRem(props?.dialogData?.fontSizeTimes * 18) + 'px',
})

const tempDom = (params) => {
  let tempDom = ''
  const tempTbClass = params?.data?.percentageYoy > 0 ? 'triangle-reverse' : ''
  const tempHbClass = params?.data?.percentageMom > 0 ? 'triangle-reverse' : ''
  const tempTbColor = params?.data?.percentageYoy > 0 ? '#01FEFF' : '#E13535'
  const tempHbColor = params?.data?.percentageMom > 0 ? '#01FEFF' : '#E13535'

  switch(props?.sunBurstData?.type) {
    case 1:
      tempDom = '<br/>' + `<div style="display: flex; align-items: center"><div class="triangle ${tempTbClass}"></div>&nbsp;<span style="color: ${tempTbColor}">${params.data?.percentageYoy}%</span>` + `&nbsp;同比</div>`
          + `<div style="display: flex; align-items: center"><div class="triangle ${tempHbClass}"></div>&nbsp;<span style="color: ${tempHbColor}">${params.data?.percentageMom}%</span>` + `&nbsp;环比</div>`
      break
    case 2:
      tempDom = '<br/>' + `<div style="display: flex; align-items: center"><div class="triangle ${tempTbClass}"></div>&nbsp;<span style="color: ${tempTbColor}">${params.data?.percentageYoy}%</span>` + `&nbsp;同比</div>`
      break
    default:
      tempDom = ''
      break
  }
  return tempDom
}

const initEchart = () => {
  if (echartDom.value) {
    myChart.value = echarts.init(echartDom.value);
    let option = {
      color: props?.sunBurstData?.typeList?.map(x => x.color),
      tooltip: {
        formatter: (params) => {
          if (!params.name) {
            return '';
          }
          if (params?.data?.type === 'parent') {
            return (
                `${params.name}面积：${params.value}万㎡` + '<br/>' +
                `占比：${params.data?.percentage}%` + tempDom(params)
            );
          } else {
            return (
                `${params.treePathInfo[1].name}-${params.name}面积：${params.value}万㎡` + '<br/>' +
                `占比：${params.data?.percentage}%` + tempDom(params)
            );
          }
        }
      },
      series: {
        type: 'sunburst',
        radius: ['50%', '100%'],
        label: {
          show: false
        },
        itemStyle: {
          color: 'transparent',
          borderWidth: 0
        },
        data: props?.sunBurstData?.seriesData
      }
    }
    option && myChart.value.setOption(option, true);

    myChart.value.on('click', (params) => {
      if (!params?.data?.name) {
        isGroundFloor.value = true
        emit('changeFloor', { name: '总', percentage: 100 })
      }
      if (params?.data?.type === 'parent') {
        isGroundFloor.value = false
        currentChildrenLegendMainName.value = params?.name
        emit('changeFloor', params)
      }
    })

    myChart.value.getZr().on('click', function(event) {
      // 没有 target 意味着鼠标/指针不在任何一个图形元素上，它是从“空白处”触发的。
      if (!event.target && isGroundFloor.value) {
        emit('magnifyChart')
      }
      if (!event.target && !isGroundFloor.value) {
        // 点击在了空白处，做些什么。
        emit('changeFloor', { name: '总', percentage: 100 })
        updateChart();
      }
    });
  }
}

const changeTabs = (val) => {
  if (val.isDisabled) return;
  emit('changeLegend', val)
  emit('dialogEmit', {type: props?.sunBurstData?.moduleName, value: val})
}

const changeFontSize = () => { // 动态改变字体大小方法
  magnifyFontSizeObj.value = {
    '--custom-font-size-10': pxToRem(props?.dialogData?.fontSizeTimes * 10) + 'px',
    '--custom-font-size-12': pxToRem(props?.dialogData?.fontSizeTimes * 12) + 'px',
    '--custom-font-size-14': pxToRem(props?.dialogData?.fontSizeTimes * 14) + 'px',
    '--custom-line-height-18': pxToRem(props?.dialogData?.fontSizeTimes * 18) + 'px',
  }
}

const updateChart = () => {
  if (myChart.value) {
    myChart.value.dispose(); // 销毁旧图表实例
  }
  isGroundFloor.value = true
  changeFontSize();
  initEchart();
};


defineExpose({
  updateChart
})

onMounted(() => {
  initEchart();
  window.addEventListener("resize", updateChart);
})

onUnmounted(() => {
  window.removeEventListener("resize", updateChart);
})
</script>

<style scoped lang="less">
.h185 {
  height: 185px;
}

.h165 {
  height: 165px;
}

.dialog-h185 {
  width: 919px;
  height: 500px;
}

.content-title {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;

  > span {
    font-size: var(--custom-font-size-14);
    color: white;
  }

  .content-title-label {
    margin-bottom: 8px;
  }

  .content-title-right {
    display: flex;
    flex: 1;
    justify-content: flex-end;

    .el-row {
      width: 100%;

      .el-col {
        display: flex;
        align-items: center;
      }
    }

    .multiple-row {
      margin-top: var(--custom-font-size-10);
    }

    .content-title-item {
      display: flex;
      align-items: center;
      color: white;

      > div:first-child {
        width: var(--custom-font-size-10);
        height: var(--custom-font-size-10);
        margin-right: 3px;
      }

      > div:last-child {
        font-size: var(--custom-font-size-12);
      }
    }

    .content-title-item:not(:last-child) {
      margin-right: 10px;
    }
  }
}
:deep(.triangle) {
  width: 0;
  height: 0;
  border: 5px solid transparent;
  border-top: 5px solid #E13535;
  border-bottom: 0;
  display: inline-flex;
  align-items: center;
  margin-right: 5px;
}

:deep(.triangle-reverse) {
  transform: rotate(180deg);
  border-top: 5px solid #01FEFF;
}
</style>